package com.wit.witmg.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wit.witmg.constants.SysConstants;
import com.wit.witmg.entity.TECdata;
import com.wit.witmg.entity.TECdata;
import com.wit.witmg.entity.TTjdzpcom;
import com.wit.witmg.mapper.TECdataMapper;
import com.wit.witmg.mapper.TTjdzpcomMapper;
import com.wit.witmg.service.ITECdataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wit.witmg.service.ITTjdzpcomService;
import com.wit.witmg.util.DateUtil;
import com.wit.witmg.util.ErrorCode;
import com.wit.witmg.util.JsonResult;
import com.wit.witmg.util.StringUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;

/**
 * @author bob
 * @since 2025-03-25
 */
@Service
@RequiredArgsConstructor
public class TECdataServiceImpl extends ServiceImpl<TECdataMapper, TECdata> implements ITECdataService {
    final TTjdzpcomMapper tjMapper;

    @Override
    @Transactional(rollbackFor = {java.lang.Exception.class})
    public Object add(HttpServletRequest request,String sn, String json) {
        if(sn!=null && !sn.equals(SysConstants.SN)){
            return JsonResult.error(ErrorCode.ERR_406);
        }
        try {
            String fileName= DateUtil.getCurDateTime()+"_tecdata.txt";
            fileName=fileName.replace(":","_");
            String filePath = StringUtils.instance.getLogDir() +fileName;
            Files.write(Paths.get(filePath), json.getBytes());
        }catch (Exception e){
            System.out.println(e.getMessage());
        }
        List<TECdata> list= JSONObject.parseArray(json,TECdata.class);
        if(list!=null){
            boolean bl= saveBatch(list);
            if(bl){
                return JsonResult.success("上传成功");
            }
        }
        return JsonResult.error(ErrorCode.ERR_504);
    }

    @Override
    public Object get(HttpServletRequest request, String ph, String xh,boolean bl) {//bl为true时才需要统计
        QueryWrapper<TECdata> qw=new QueryWrapper<>();
        qw.eq("PiHao",ph);
        if(ph!=null && xh!=null){
            qw.eq("XuHao",xh);
            qw.last("limit 1");
            return JsonResult.success(getOne(qw));
        }
        if(ph!=null){//批号查询返回值包括：第一条时间、最后一条的时间，样品数，合格率，试验结果的平均值，总体标准差。
            List<TECdata> list=list(qw);
            if(!bl) {
                return JsonResult.success(list);
            }
           //添加到统计表
                // 获取第一条时间
            QueryWrapper<TECdata> firstTimeQw = new QueryWrapper<>();
            firstTimeQw.eq("PiHao", ph);
            firstTimeQw.orderByAsc("RiQi").last("limit 1");
            TECdata firstRecord = getOne(firstTimeQw);
            if (firstRecord == null) {
                return JsonResult.error(ErrorCode.ERR_313);
            }

            String firstTime = firstRecord.getRiQi();

            // 获取最后一条时间
            QueryWrapper<TECdata> lastTimeQw = new QueryWrapper<>();
            lastTimeQw.eq("PiHao", ph);
            lastTimeQw.orderByDesc("RiQi").last("limit 1");
            TECdata lastRecord = getOne(lastTimeQw);
            String lastTime = lastRecord != null ? lastRecord.getRiQi() : null;

            // 获取样品数
            QueryWrapper<TECdata> countQw = new QueryWrapper<>();
            countQw.eq("PiHao", ph);
            int sampleCount = count(countQw);

            // 获取合格率
            QueryWrapper<TECdata> qualifiedCountQw = new QueryWrapper<>();
            qualifiedCountQw.eq("PiHao", ph);
            qualifiedCountQw.eq("HeGe", "1");
            int qualifiedCount = count(qualifiedCountQw);
//            double qualificationRate = sampleCount > 0 ? (double) qualifiedCount / sampleCount : 0;

            // 获取试验结果的平均值和总体标准差
            QueryWrapper<TECdata> avgU1mAQw = new QueryWrapper<>();
            avgU1mAQw.eq("PiHao", ph);
            avgU1mAQw.ne("U1mA", "no data");
            avgU1mAQw.ne("U1mA", "");
            avgU1mAQw.select("AVG(U1mA) as avgU1mA", "STDDEV_POP(U1mA) as stdU1mA"); // 假设试验结果字段为 "U1mA"
            List<Map<String, Object>> avgU1mAList = listMaps(avgU1mAQw);
            double avgU1mA = avgU1mAList.isEmpty() ? 0 : (double) avgU1mAList.get(0).get("avgU1mA");
            double stdU1mA = avgU1mAList.isEmpty() ? 0 : (double) avgU1mAList.get(0).get("stdU1mA");

            QueryWrapper<TECdata> avgIlQw = new QueryWrapper<>();
            avgIlQw.eq("PiHao", ph);
            avgIlQw.ne("Il", "no data");
            avgIlQw.ne("Il", "");
            avgIlQw.select("AVG(Il) as avgIl", "STDDEV_POP(Il) as stdIl");
            List<Map<String, Object>> avgIlList = listMaps(avgIlQw);
            double avgIl = avgIlList.isEmpty() ? 0 : (double) avgIlList.get(0).get("avgIl");
            double stdIl = avgIlList.isEmpty() ? 0 : (double) avgIlList.get(0).get("stdIl");

            QueryWrapper<TECdata> avgCanYaQw = new QueryWrapper<>();
            avgCanYaQw.eq("PiHao", ph);
            avgCanYaQw.eq("HeGe", "1");
            avgCanYaQw.ne("CanYa", "no data");
            avgCanYaQw.ne("CanYa", "");
            avgCanYaQw.select("AVG(CanYa) as avgCanYa", "STDDEV_POP(CanYa) as stdCanYa");
            List<Map<String, Object>> avgCanYaList = listMaps(avgCanYaQw);
            double avgCanYa = avgCanYaList.isEmpty() ? 0 : (double) avgCanYaList.get(0).get("avgCanYa");
            double stdCanYa = avgCanYaList.isEmpty() ? 0 : (double) avgCanYaList.get(0).get("stdCanYa");

            QueryWrapper<TECdata> avgCanYaCurrQw = new QueryWrapper<>();
            avgCanYaCurrQw.eq("PiHao", ph);
            avgCanYaCurrQw.eq("HeGe", "1");
            avgCanYaCurrQw.ne("CanYaCurr", "no data");
            avgCanYaCurrQw.ne("CanYaCurr", "");
            avgCanYaCurrQw.select("AVG(CanYaCurr) as avgCanYaCurr", "STDDEV_POP(CanYaCurr) as stdCanYaCurr");
            List<Map<String, Object>> avgCanYaCurrList = listMaps(avgCanYaCurrQw);
            double avgCanYaCurr = avgCanYaCurrList.isEmpty() ? 0 : (double) avgCanYaCurrList.get(0).get("avgCanYaCurr");
            double stdCanYaCurr = avgCanYaCurrList.isEmpty() ? 0 : (double) avgCanYaCurrList.get(0).get("stdCanYaCurr");

            QueryWrapper<TECdata> avgCanYaYaBiQw = new QueryWrapper<>();
            avgCanYaYaBiQw.eq("PiHao", ph);
            avgCanYaYaBiQw.eq("HeGe", "1");
            avgCanYaYaBiQw.ne("CanYaYaBi", "no data");
            avgCanYaYaBiQw.ne("CanYaYaBi", "");
            avgCanYaYaBiQw.select("AVG(CanYaYaBi) as avgCanYaYaBi", "STDDEV_POP(CanYaYaBi) as stdCanYaYaBi");
            List<Map<String, Object>> avgCanYaYaBiList = listMaps(avgCanYaYaBiQw);
            double avgCanYaYaBi = avgCanYaYaBiList.isEmpty() ? 0 : (double) avgCanYaYaBiList.get(0).get("avgCanYaYaBi");
            double stdCanYaYaBi = avgCanYaYaBiList.isEmpty() ? 0 : (double) avgCanYaYaBiList.get(0).get("stdCanYaYaBi");
            TTjdzpcom ent = new TTjdzpcom();
            ent.setPh(ph);
            ent.setTp("13");
            ent.setDt0(DateUtil.getDateFromString(firstTime));
            ent.setDt1(DateUtil.getDateFromString(lastTime));
            ent.setQqt((double)qualifiedCount);
            ent.setQt((double)sampleCount);
            ent.setV0(avgU1mA);
            ent.setV1(avgIl);
            ent.setV2(avgCanYa);
            ent.setV3(avgCanYaCurr);
            ent.setV4(avgCanYaYaBi);
            ent.setS0(stdU1mA);
            ent.setS1(stdIl);
            ent.setS2(stdCanYa);
            ent.setS3(stdCanYaCurr);
            ent.setS4(stdCanYaYaBi);

            QueryWrapper<TTjdzpcom> tjQw = new QueryWrapper<>();
            tjQw.eq("ph", ph);
            tjQw.eq("tp", "13");
            if(tjMapper.selectCount(tjQw) > 0){
                tjMapper.delete(tjQw);
            }
            tjMapper.insert(ent);
            return JsonResult.success(ent);

        }


        return JsonResult.error(ErrorCode.ERR_200);
    }
}
